package com.sfl.api_backend.controller.files;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sfl.api_backend.constant.HttpCode;
import com.sfl.api_backend.entity.Labelsets;
import com.sfl.api_backend.entity.Users;
import com.sfl.api_backend.mapper.LabelsetsMapper;
import com.sfl.api_backend.service.ILabelsetsService;
import com.sfl.api_backend.utils.Api.RestResult;
import com.sfl.api_backend.utils.File.DeleteFilestore;
import com.sfl.api_backend.utils.RandomID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.*;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 标签集表 前端控制器
 * </p>
 *
 * @author szc
 * @since 2023-01-27
 */
@RestController
@RequestMapping("/files/labels/labelsets")
@Slf4j
public class LabelsetsController {

    @Resource
    private ILabelsetsService labelsetsService;

    @Value("${file.upload.path}")
    private String uploadPath;

    @PostMapping("/make")
    @PreAuthorize("hasAuthority('User')")
    public RestResult make(@RequestBody Labelsets labelsets) {
        try {
            log.info("Make labelsets: {}", labelsets);
            labelsets.setLabelsetId(RandomID.getRandomID());

            String labelsetPath = uploadPath + labelsets.getUserId() + "/labelsets/" + labelsets.getImgsetId() + "/";
            labelsets.setLabelsetPath(labelsetPath);

            // mkdir
            File file = new File(labelsetPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            // set time
            LocalDateTime now = LocalDateTime.now();
            labelsets.setCreateTime(now);
            labelsets.setLabelsetId(RandomID.getRandomID());

            // save
            labelsetsService.save(labelsets);
            return RestResult.success();
        } catch (Exception e) {
            log.error("Make labelsets: {} error", labelsets);
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }

    @PostMapping("/modify")
    @PreAuthorize("hasAuthority('User')")
    public RestResult modifly(@RequestBody Labelsets labelsets) {
        try {
            log.info("Modifly labelsets: {}", labelsets);
            Wrapper<Labelsets> wrapper = new LambdaQueryWrapper<>();
            ((LambdaQueryWrapper<Labelsets>) wrapper).eq(Labelsets::getLabelsetId, labelsets.getLabelsetId());

            Labelsets tmp = labelsetsService.getOne(wrapper);
            tmp.setLabelsetName(labelsets.getLabelsetName());
            labelsetsService.updateById(tmp);

            return RestResult.success();
        } catch (Exception e) {
            log.error("Modifly labelsets: {} error", labelsets);
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }

    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('User')")
    public RestResult delete(@RequestBody List<String> labelsetIds) {
        try {
            log.info("Delete labelsets: {}", labelsetIds);

            List<Labelsets> labelsets = labelsetsService.listByIds(labelsetIds);
            // 删除文件
            for(Labelsets set : labelsets){
                // remove file
                File rootFile = new File(set.getLabelsetPath());
                DeleteFilestore.deleteFile(rootFile);
            }

            labelsetsService.removeByIds(labelsetIds);
            return RestResult.success();
        } catch (Exception e) {
            log.error("Delete labelsets: {} error", labelsetIds);
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }

    @PostMapping("/list")
    @PreAuthorize("hasAuthority('User')")
    public RestResult list(@RequestBody Users vo){
        try{
            log.info("List labelsets: {}", vo.getUserId());
            Wrapper<Labelsets> wrapper = new LambdaQueryWrapper<>();
            ((LambdaQueryWrapper<Labelsets>) wrapper).eq(Labelsets::getUserId, vo.getUserId());
            List<Labelsets> labelsets = labelsetsService.list(wrapper);
            return RestResult.success(labelsets);
        }
        catch (Exception e){
            log.error("List labelsets: {} error", vo.getUserId());
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }

    @PostMapping("/analysis")
    @PreAuthorize("hasAuthority('User')")
    public RestResult analysis(@RequestBody Labelsets vo){
        try{
            log.info("List labelsets: {}", vo.getLabelsetId());
            return labelsetsService.analysis(vo);
        }
        catch (Exception e){
            log.error("List labelsets: {} error", vo.getUserId());
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }

}
